package com.findyou.headline.filters;


import com.findyou.headline.common.Result;
import com.findyou.headline.common.ResultCodeEnum;
import com.findyou.headline.util.JwtHelper;
import com.findyou.headline.util.WebUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/headline/*") // 设置拦截的地址 你只要访问这个 我都去拦截一下 注意 不是什么都要去拦截的
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String token = request.getHeader("token");
        boolean flag = false;

        if(null != token && !JwtHelper.isExpiration(token)) {
            flag = true; // 不为空 且没过期
        }

        if(flag) { // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            WebUtil.writeJson(response, Result.build(null, ResultCodeEnum.NOTLOGIN));
        }
    }
}
